import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 请求合并器使用示例
 */
public class RequestMergerExample {
    
    public static void main(String[] args) throws InterruptedException {
        // 创建请求合并器，设置请求有效期为5秒
        RequestMerger<String, String> merger = new RequestMerger<>(5000);
        
        // 模拟高并发请求
        for (int i = 0; i < 100; i++) {
            final int index = i;
            new Thread(() -> {
                try {
                    // 模拟三种不同的请求
                    String requestKey = "request_" + (index % 3);
                    
                    // 执行请求
                    CompletableFuture<String> future = merger.execute(requestKey, key -> {
                        // 模拟实际的请求处理逻辑
                        System.out.println("实际执行请求: " + key + " 线程: " + Thread.currentThread().getName());
                        
                        try {
                            // 模拟请求处理时间
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        
                        return "结果: " + key + " 时间: " + System.currentTimeMillis();
                    });
                    
                    // 获取结果
                    String result = future.get();
                    System.out.println("线程 " + index + " 获取结果: " + result);
                    
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }).start();
            
            // 控制请求发送速率，模拟真实场景
            if (i % 10 == 0) {
                Thread.sleep(100);
            }
        }
        
        // 等待所有请求完成
        Thread.sleep(10000);
        
        // 关闭合并器
        merger.shutdown();
    }
}